/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.core.image.web.filter.ImageCheckFilter
   Module Description   :

   Date Created      : 2010/3/18
   Original Author   : jeff.ma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.core.image.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.image.web.servlet.TextImageServlet;

/**
 * @author jeff.ma
 * 
 */
public class ImageCheckFilter implements Filter {

	/** default constructor */
	public ImageCheckFilter() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO_jeffma Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
	 * javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = ServerValue.getFrontHostname() + httpRequest.getRequestURI();

		if (StringUtils.isNotBlank(httpRequest.getQueryString())) {
			uri += "?" + httpRequest.getQueryString();
		}

		String key = (String) httpRequest.getSession().getAttribute(TextImageServlet.SESSION_KEY);
		String input = httpRequest.getParameter("textImage");
		if (StringUtils.isBlank(input)) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp?errorMsg=code_error");
		} else if (!input.equals(key)) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp?errorMsg=code_error");
		} else {
			httpRequest.getSession().removeAttribute(TextImageServlet.SESSION_KEY);
			chain.doFilter(request, response);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
